package com.example.mydataapplication;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class SQLite extends Fragment {
    private dbHelper dbHelper;
    public SQLite(){
        super(R.layout.sqljiemian);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        dbHelper=new dbHelper(getContext());
        EditText e1=getView().findViewById(R.id.textView2);
        EditText e2=getView().findViewById(R.id.textView4);
        getView()
                .findViewById(R.id.button7)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SQLiteDatabase database=dbHelper.getWritableDatabase();
                        ContentValues values=new ContentValues();
                        values.put("username",e1.getText().toString());
                        values.put("age",e2.getText().toString());
                        Toast.makeText(getActivity(),
                                database.insert("users",null,values) ==-1?
                                "添加失败" : "添加成功",
                                Toast.LENGTH_LONG).show();
                        database.close();
                    }
                });
        TextView textView=getView().findViewById(R.id.textView6);
        getView()
                .findViewById(R.id.button8)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SQLiteDatabase database=dbHelper.getReadableDatabase();
                        Cursor cursor=database.query("users",null,"age<18",null,null,null,null);
                        StringBuilder stringBuilder=new StringBuilder();
                        while (cursor.moveToNext()){
                            stringBuilder.append("id:")
                                    .append(cursor.getLong(cursor.getColumnIndex("id")))
                                    .append("   username")
                                    .append(cursor.getString(cursor.getColumnIndex("username")))
                                    .append("   age")
                                    .append(cursor.getLong(cursor.getColumnIndex("age")))
                                    .append("\n");
                        }
        textView.setText(stringBuilder.toString());
                    }
                });
    }
}